﻿using System.Threading.Tasks.Dataflow;
using System;
using System.Collections;
using System.Text;
using UMC.Data;
using UMC.Data.Sql;
using UMC.Net;
using UMC.Web.UI;
using UMC.Web;

namespace UMC.ITME.Activities
{
    [Apiumc("System", "License", Auth = WebAuthType.Admin, Desc = "系统注册")
    ]
    class SiteLicenseActivity : WebActivity
    {
        static string RegisterToken;

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var appId = WebResource.Instance().Provider["appId"];
            var secret = WebResource.Instance().Provider["appSecret"];

            var model = this.AsyncDialog("Model", d =>
             {

                 if (String.IsNullOrEmpty(appId) || String.IsNullOrEmpty(secret))
                 {
                     return this.DialogValue("Select");
                 }
                 var webr2 = new Uri(APIProxy.Uri, "Transfer").WebRequest();

                 var ui = UISection.Create(new UITitle("授权信息"));
                 String resultStr = APIProxy.Sign(webr2, secret).Get(out var xhr);

                 switch (xhr.StatusCode)
                 {
                     case System.Net.HttpStatusCode.Unauthorized:
                     case System.Net.HttpStatusCode.Forbidden:
                         this.Context.Send("noLicense", false);
                         response.Redirect(request.Model, request.Command, new UIConfirmDialog(resultStr ?? "检验不通过或注册信息有误,请从新注册") { DefaultValue = "Select" });

                         break;
                 }
                 var meta = JSON.Deserialize<WebMeta>(resultStr) ?? new WebMeta();

                 ui.AddCell("授权版本", meta["license"]);

                 ui.AddCell("主体名称", meta["caption"], new UIClick(request.Model, request.Command, new WebMeta(d, "Name")))
                  .AddCell("主体所在地", meta["address"], new UIClick(request.Model, request.Command, new WebMeta(d, "Address")));


                 ui.NewSection().AddCell("联系人", meta["contact"], new UIClick(request.Model, request.Command, new WebMeta(d, "Name")))
                 .AddCell("联系电话", meta["tel"], new UIClick(request.Model, request.Command, new WebMeta(d, "Name")))
                 .AddCell("电子邮件", meta["email"], new UIClick(request.Model, request.Command, new WebMeta(d, "Email")));

                 var skey = meta["key"];
                 var domain = meta["domain"];
                 var now = Utility.TimeSpan();
                 if (meta.ContainsKey("sign") && meta.ContainsKey("signKey"))
                 {
                     License.Put(meta["signKey"].Split(","), meta["sign"]);
                 }


                 if (System.Net.IPAddress.TryParse(meta.Get("dns"), out var ipAddr))
                 {
                     DnsServer.IterativeDNS = new System.Net.IPEndPoint(ipAddr, 53);
                 }
                 var lui = ui.NewSection();


                 var apps = meta.GetDictionary()["certs"] as Array;
                 var cl = apps?.Length;
                 for (var i = 0; i < cl; i++)
                 {
                     var hash = apps.GetValue(i) as System.Collections.Hashtable;
                     var code = hash["Code"] as string;
                     var click = new UIClick(request.Model, request.Command, code);
                     switch (hash["Code"] as string)
                     {
                         case "UserSession":
                             lui.AddCell('\uf260', String.Format("{0}会话规模", hash["Quantity"]), hash["Expire"] as string, click);
                             break;
                         case "WebSSH":
                             lui.AddCell('\uf260', String.Format("{0}设备", hash["Quantity"]), hash["Expire"] as string, click);

                             break;
                         default:
                             lui.AddCell('\uf260', String.Format("{0}{1}", hash["Quantity"], hash["Code"]), hash["Expire"] as string, click);

                             break;
                     }
                 }

                 if (lui.Length == 0)
                 {
                     lui.Add("Desc", new UMC.Web.WebMeta().Put("desc", "还未有应用许可,请去获得许可").Put("icon", "\uea05"), new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"),
                    new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                 }
                 var ver = APIProxy.Version.Split('-', '+')[0];
                 ui.NewSection().AddCell("运行版本", ver)
                 .NewSection().AddCell("联系官方", "让天才工程师为你服务", new UIClick(request.Model, request.Command, "Contact"));

                 ui.UIFootBar = new UIFootBar() { IsFixed = true };
                 ui.UIFootBar.AddText(new UIEventText("重置授权码").Click(new UIClick(request, d, "Select")),
                     new UIEventText("去获得许可").Click(new UIClick(request.Model, request.Command, "UserSession")).Style(new UIStyle().BgColor()));

                 ui.SendTo("noLicense", this.Context, "License");
                 return this.DialogValue("none");
             });
            switch (model)
            {
                case "Select":

                    if (String.IsNullOrEmpty(RegisterToken) == false)
                    {
                        var rwebr = new Uri(APIProxy.Uri, "/Register").WebRequest();
                        rwebr.Add("umc-client-pfm", "sync");
                        rwebr.Add("umc-app-version", APIProxy.Version);
                        var result = rwebr.Post(new WebMeta().Put("token", RegisterToken, "type", "Register"), out var resp);

                        if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            var meta = JSON.Deserialize<WebMeta>(result);

                            if (meta.ContainsKey("success"))
                            {
                                RegisterToken = String.Empty;
                                var provider = UMC.Data.WebResource.Instance().Provider;
                                var pc = Reflection.Configuration("assembly") ?? new ProviderConfiguration();
                                pc.Add(provider);

                                provider.Attributes["appSecret"] = meta["appSecret"];
                                provider.Attributes["appId"] = meta["appId"];
                                // Context.Client.Context.

                                if (this.Context.Client.Context is HttpMimeContext)
                                {
                                    HttpMimeContext httpMimeContext = (HttpMimeContext)this.Context.Client.Context;
                                    httpMimeContext.AllowFingerprint();
                                }
                                Reflection.Configuration("assembly", pc);
                                this.Prompt("检测到已经注册了.", false);
                                this.Context.Send(new UISectionBuilder(request.Model, request.Command)
                                    .RefreshEvent("License")
                                    .Builder(), true);

                            }

                        }
                    }
                    response.Redirect(request.Model, request.Command, "Register");

                    break;
                case "Register":
                    {
                        var token = UMC.Data.Utility.Guid(this.Context.Token.Device.Value);
                        var rwebr = new Uri(APIProxy.Uri, "/Register").WebRequest();
                        rwebr.Add("umc-client-pfm", "sync");
                        RegisterToken = token;
                        rwebr.Add("umc-app-version", APIProxy.Version);
                        var result = rwebr.Post(new WebMeta().Put("token", token, "type", "Register"), out var resp);

                        if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            var meta = JSON.Deserialize<WebMeta>(result);

                            if (meta.ContainsKey("success"))
                            {
                                var provider = UMC.Data.WebResource.Instance().Provider;
                                var pc = Reflection.Configuration("assembly") ?? new ProviderConfiguration();
                                pc.Add(provider);

                                provider.Attributes["appSecret"] = meta["appSecret"];
                                provider.Attributes["appId"] = meta["appId"];

                                RegisterToken = String.Empty;
                                Reflection.Configuration("assembly", pc);
                                this.Prompt("注册登记成功", false);
                                this.Context.Send("License", false);
                                if (this.Context.Client.Context is HttpMimeContext)
                                {
                                    HttpMimeContext httpMimeContext = (HttpMimeContext)this.Context.Client.Context;
                                    httpMimeContext.AllowFingerprint();
                                }

                                this.Context.Send(new UISectionBuilder(request.Model, request.Command)
                                    .RefreshEvent("License")
                                    .Builder(), true);

                            }
                            else if (meta.ContainsKey("url"))
                            {
                                var Config = this.AsyncDialog("Config", g =>
                                {
                                    var fm = new UIFormDialog() { Title = "登记授权" };
                                    fm.Add(new UIQRCode(meta["url"]));
                                    fm.Menu(new UIClick(request, "Model", "License") { Text = "授权码" });

                                    fm.AddFooter(meta["desc"] ?? "请用微信扫一扫上图二维码，完成登记授权", "token", token);

                                    fm.Submit("下一步", "License");
                                    this.Context.Send("Fingerprint", new WebMeta("SessionKey", token), false);
                                    fm.AddFooter(meta["tip"] ?? "当在微信中完成登记时，请点击“下一步”，完成登记信息同步");
                                    return fm;
                                });
                                if (meta.ContainsKey("msg"))
                                {
                                    this.Prompt(meta["msg"]);
                                }

                            }
                            else if (meta.ContainsKey("msg"))
                            {
                                this.Prompt(meta["msg"]);
                            }
                        }
                        else
                        {
                            this.Prompt("注册时通信异常");
                        }
                    }
                    break;
                case "Contact":
                    {

                        var context = new Uri(APIProxy.Uri, $"/UMC/Platform/Contact/{APIProxy.Version}").WebRequest().Get(out var _);
                        response.Redirect(JSON.Expression(context));
                    }
                    break;

                case "License":
                    {
                        var provider = UMC.Data.WebResource.Instance().Provider;
                        var Config = this.AsyncDialog("Config", g =>
                        {
                            var fm = new UIFormDialog() { Title = "应用授权" };
                            fm.AddText("授权码", "appId", String.Empty);
                            fm.AddText("检验码", "appSecret", "");

                            fm.Submit("确认授权", "License");
                            return fm;
                        });
                        var appId2 = Utility.Guid(Config["appId"]);
                        if (appId2.HasValue == false)
                        {
                            this.Prompt("不存在此标识码格式");
                        }
                        var webR = new Uri(APIProxy.Uri, $"/{Utility.Parse36Encode(appId2.Value)}/Transfer/").WebRequest();

                        var result = APIProxy.Sign(webR, Config["appSecret"]).Get(out var resp);
                        if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            var con = UMC.Data.JSON.Deserialize(result) as Hashtable;
                            var pc = Reflection.Configuration("assembly") ?? new ProviderConfiguration();
                            pc.Add(provider);
                            RegisterToken = String.Empty;

                            provider.Attributes["appSecret"] = Config["appSecret"];
                            provider.Attributes["appId"] = con["appId"] as string;
                            if (this.Context.Client.Context is HttpMimeContext)
                            {
                                HttpMimeContext httpMimeContext = (HttpMimeContext)this.Context.Client.Context;
                                httpMimeContext.AllowFingerprint();
                            }

                            Reflection.Configuration("assembly", pc);
                            this.Prompt("注册登记成功", false);
                            this.Context.Send("License", false);

                            this.Context.Send(new UISectionBuilder(request.Model, request.Command)
                                .RefreshEvent("License")
                                .Builder(), true);
                        }
                        else
                        {
                            this.Prompt("效验不通过，请核查授权信息");
                        }

                    }
                    break;
            }

            if (String.IsNullOrEmpty(secret))
            {
                this.Prompt("效验码不存在");
            }
            var webr = new Uri(APIProxy.Uri, "Transfer").WebRequest();
            APIProxy.Sign(webr, secret);

            var applyS = this.AsyncDialog(g =>
            {
                var meta = JSON.Deserialize<WebMeta>(webr.Get(out var _));
                var caption = meta["contact"];
                var fm = new UMC.Web.UIFormDialog() { Title = "授权信息" };
                switch (model)
                {
                    // default:
                    case "Name":
                        fm.Title = "主体登记";
                        fm.AddText("主体名称", "Name", meta["caption"]).PlaceHolder("所属公司或门店名称");
                        fm.AddText("联系人姓名", "Contact", meta["contact"]).Put("placeholder", "联系人真实人名");
                        fm.AddPhone("手机号码", "Tel", meta["tel"]).Put("placeholder", "真实的手机号码");
                        break;
                    case "Email":
                        fm.Title = "主体登记";
                        fm.AddText("电子邮件", "Email", meta["email"]).Put("placeholder", "建议联系人QQ邮箱");
                        break;
                    case "Address":
                        fm.Title = "主体登记";
                        fm.AddOption("主体所在地", "Address", meta["address"], meta["address"]).PlaceHolder("公司或门店地址")
                        .Command("Settings", "Area");
                        break;
                    default:
                        var data = JSON.Deserialize<System.Collections.Hashtable>(webr.Post(new WebMeta().Put("type", "App", "Code", model), out var _));
                        if (data.ContainsKey("msg"))
                        {
                            this.Prompt(data["msg"] as string);
                        }
                        if (data.ContainsKey("BuySrc"))
                        {
                            request.Arguments["API"] = data["BuySrc"] as string;
                        }
                        if (data.Contains("sign") && data.Contains("code"))
                        {
                            License.Put(data["code"] as string, data["sign"] as string);
                        }
                        var Combo = data["Combo"] as Array;

                        fm.Title = "功能授权";
                        var style = new UIStyle();
                        style.Name("icon").Color(0x09bb07).Size(84).Font("wdk");
                        style.Name("title").Color(0x333).Size(20);
                        style.BgColor(0xfafcff).Height(200).AlignCenter();
                        var desc = new UMC.Web.WebMeta().Put("title", (data["Desc"] as string) ?? "应用许可").Put("icon", (data["Icon"] as string) ?? "\uea04");
                        fm.Config.Put("Header", new UIHeader().Desc(desc, "{icon}\n{title}", style));

                        fm.AddTextValue().Put("当前许可", data["Name"] as string).Put("许可时效", data["Expire"] as string);
                        var f = fm.AddRadio("服务套餐", "Quantity");
                        var cl = Combo.Length;
                        for (var i = 0; i < cl; i++)
                        {
                            var hash = Combo.GetValue(i) as System.Collections.Hashtable;
                            f.Put(hash["Text"] as string, hash["Value"] as string, i == cl - 1);
                        }
                        //
                        fm.Config.Put("Action", true);

                        fm.Submit("确认去授权");
                        return fm;

                }

                fm.Submit("确认提交", "License");
                return fm;
            }, "Setings");
            switch (model)
            {
                // default:
                case "Tel":
                case "Email":
                case "Contact":
                case "Name":
                case "Address":
                    {
                        var meta = JSON.Deserialize<WebMeta>(webr.Post(applyS.Put("type", "Contact"), out var _));
                        if (meta.ContainsKey("msg"))
                        {
                            this.Prompt(meta["msg"]);
                        }
                        if (meta.ContainsKey("success"))
                        {
                            this.Context.Send("License", true);
                        }
                    }
                    break;
                default:
                    var src = applyS["API"];
                    var Quantity = applyS["Quantity"];
                    response.Redirect(new Uri($"{src}&Combo=1&Quantity={Quantity}"));
                    break;
            }



        }

    }
}
